package com.jackrain.nea.omslocal.util;

import com.alibaba.fastjson.JSONArray;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @Discription: 平均拆分 jsonarr
 * Created with IntelliJ IDEA.
 * @Author cs
 * @Date 2018/3/21 10:42
 */
@Component
@Slf4j
public class SplitArrUtil {

    public JSONArray splitArr(JSONArray jsonArray, int count) {

        JSONArray resultJsonArr = new JSONArray();

        if (jsonArray == null || count < 1) {
            // 为空,或 数量小于1 异常
            return null;
        }
            int size = jsonArray.size();
            if (size <= count) {
                //数据量不足count指定的大小
                resultJsonArr.add(jsonArray);
            } else {
                int pre = size / count;
                int last = size % count;
                //前面 pre 个集合，每个大小都是均分 count个元素
                for (int i = 0; i < pre; i++) {
                    JSONArray tempArr = new JSONArray();
                    for (int j = 0; j < count; j++) {
                        tempArr.add(jsonArray.get(i * count + j));
                    }
                    resultJsonArr.add(tempArr.toJSONString());
                }
                //last处理
                if (last > 0) {
                    JSONArray jsonArr = new JSONArray();
                    for (int i = 0; i < last; i++) {
                        jsonArr.add(jsonArray.get(pre * count + i));
                    }
                    resultJsonArr.add(jsonArr.toJSONString());
                }
            }
        return resultJsonArr;
    }
}



